#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

#define DKYTGY 175312
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
int serverfd, clientfd;
char buffer[BUFSIZ];

void *wc(void *m){
    pthread_mutex_lock( &counter_mutex );
    int len, i;
    long wordscount=0;
    int flag=1;
    while(1){
        if((len=recv(clientfd, buffer, 1024, 0))>0){
            for(i=0; i<len; i++){
                if(flag==0){
                    switch(buffer[i]){
                        case ' ':
                            wordscount++;
                            break;
                        case '\n':
                            wordscount++;
                            break;
                        case '\r':
                            wordscount++;
                            break;
                        default:
                            break;
                    }
                }
                if(buffer[i]== ' ' || buffer[i]=='\n' || buffer[i]=='\r')
                    flag=1;
                else
                    flag=0;
            }
        }
        if(len<1024)
            break;
    }
    send(clientfd, &wordscount, sizeof(long), 0);
    close(clientfd);
    pthread_mutex_unlock( &counter_mutex );
    return NULL;
}
void main(){
    pthread_t t;
    char arg[30];

    struct sockaddr_in my_addr;
    struct sockaddr_in remote_addr;

    memset(&my_addr, 0, sizeof(my_addr));
    my_addr.sin_family=AF_INET;
    my_addr.sin_addr.s_addr=INADDR_ANY;
    my_addr.sin_port=htons(DKYTGY);

    if((serverfd=socket(PF_INET, SOCK_STREAM, 0))==-1){
        perror("socket");
    }

    if(bind(serverfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))<0){
        perror("bind");
    }
    listen(serverfd, 5);
    int addrlen=sizeof(struct sockaddr_in);
    while(1){
        if((clientfd=accept(serverfd, (struct sockaddr *)&remote_addr, &addrlen))<0){
            perror("accept");
        }
        printf("accept client %s\n", inet_ntoa(remote_addr.sin_addr));
        pthread_create(&t, NULL, &wc, NULL);
        pthread_join(&t, NULL);
    }
    close(serverfd);
}
